package test.patterns;

/** Demonstration of the Proxy Pattern.

This source code is from the book 
  "Flexible, Reliable Software:
    Using Patterns and Agile Development"
  published 2010 by CRC Press.
Author: 
  Henrik B Christensen 
  Computer Science Department
  Aarhus University

This source code is provided WITHOUT ANY WARRANTY either 
expressed or implied. You may study, use, modify, and 
distribute it for non-commercial purposes. For any 
commercial use, see http://www.baerbak.com/
 */
public class ProxyDemo {
	public static void main(String[] args) {
		System.out.println( "======= Demonstration of Proxy =======");
		WordProcessor wp = new WordProcessor();

		System.out.println( "--- Loading document (no image load) ---");
		wp.load("mydocument.doc");

		System.out.println( "--- Showing page 1 ---");
		wp.showPage(1);

		System.out.println( "--- Showing page 2 (image load) ---");
		wp.showPage(2);

		System.out.println( "--- Back to page 1 ---");
		wp.showPage(1);

		System.out.println( "--- And again showing page 2 (no load)---");
		wp.showPage(2);
	}
}

/** This class plays the client role for the subject */
class WordProcessor {
	private String textPage1, textPage2;
	private Image imagePage2;

	public void load(String filename) {
		// I ignore the file name :)
		textPage1 = "This is the text of page 1, that has no images.";
		textPage2 = "This is another text, on page 2, with a single image.";
		imagePage2 = new ProxyImage();
		imagePage2.load("flower.jpg");
	}

	public void showPage(int number) {
		if ( number == 1 ) {
			System.out.println( textPage1 );
		} else if ( number == 2 ) {
			System.out.println( textPage2 );
			System.out.println( imagePage2.show() );

		}
	}    
}                         

/** This interface is the Subject role: here an Image. 
 * No real functionality is provided, only the ideas.
 */
interface Image {
	public void load(String filename);
	/** show the image (here return a description string) */
	public String show();
}

/** The real subject: a jpg image */
class JPGImage implements Image {
	private String filename;
	public void load(String filename) {
		System.out.println( "*** JPGImage reading from file:"+filename+" ***");
		this.filename = filename;
	}
	public String show() {
		return "Showing JPG image from file "+filename;
	}
}

/** The proxy */
class ProxyImage implements Image {
	private String filename;
	private Image realSubject;
	public void load(String filename) {
		// just remember the filename
		this.filename = filename;
		realSubject = null;
	}
	public String show() {
		if ( realSubject == null ) {
			realSubject = new JPGImage();
			realSubject.load(filename);
		}
		return realSubject.show();
	}
}